package domain.facade;

import dao.FilesDao;
import dao.pojo.Files;
import dao.pojo.Users;
import domain.FileFacade;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: winstars
 * Date: 2007-3-1
 * Time: 18:27:21
 * To change this template use File | Settings | File Templates.
 */
class FileService implements FileFacade {
    private String tempLocation="c:\\temp";

    private String saveLocation="c:\\uploaded\\";

    protected String getTempLocation() {
        return tempLocation;
    }

    public void setTempLocation(String tempLocation) {
        this.tempLocation = tempLocation;
    }

    protected String getSaveLocation() {
        return saveLocation;
    }

    public void setSaveLocation(String saveLocation) {
        this.saveLocation = saveLocation;
    }

    private FilesDao filesDao;

    protected FilesDao getFilesDao() {
        return filesDao;
    }

    public void setFilesDao(FilesDao filesDao) {
        this.filesDao = filesDao;
    }

    public ArrayList<Files> getAllFiles() {
        return filesDao.getAllFiles();
    }

	public void uploadFiles(HttpServletRequest request) {
		String file_info=null;
		
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		// 生成文件工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(10240000); //10MB缓冲
        factory.setRepository(new File(tempLocation));

        // 生成文件上载器
        ServletFileUpload upload = new ServletFileUpload();
        upload.setFileItemFactory(factory);
        upload.setSizeMax(10240000);//10MB最大大小

        // 解析请求
        List /* FileItem */ items=null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

        Iterator iter = items.iterator();//遍历解析结果
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            
            if(item.isFormField()){
            	if(item.getFieldName().equals("file_info")){
            		file_info=item.getString();
            	}
            }else if (!item.isFormField()) {//保存非表单物件
                String name = item.getName(); //获取文件名
                name = name . substring(name.lastIndexOf('\\')+1);
                
                Long value = item.getSize();//获取文件大小
                File uploaded=new File(new StringBuilder().append(saveLocation).append(name).toString());
                try {
                    item.write(uploaded);//保存上传的文件
                    
                    //生成文件信息
                    Files file=new Files();
                    file.setFileInfo(file_info);
                    file.setFileName(name);
                    file.setFileSize(String.valueOf(value));
                    file.setUser((Users)request.getSession().getAttribute("login_user"));
                    file.setSubmitTime(new Date());
                    addFiles(file);//保存文件信息到数据库
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
	}

	public void addFiles(Files file) {
		filesDao.addFile(file);
		
	}

	public void deleteFiles(Files file) {
		filesDao.deleteFileById(file);
		
	}

	public void downFiles(Files file,ServletOutputStream out) {
        try
        {
            BufferedInputStream in = null;
            FileInputStream stream;
            try {
				stream = new FileInputStream(new File(saveLocation+file.getFileName()));//获取文件流

                int bytesRead;
                final int length = 8192;
                byte[] buffer = new byte[length];
                while ((bytesRead = stream.read(buffer, 0, length)) != -1) { //将文件流写到输出流
                    out.write(buffer, 0, bytesRead);
                }
            } catch (IOException e) {
            	if (in != null)
                {
                    in.close();
                 }
                if (out != null) 
                {
                    out.close();
                 }
            } 
            finally 
            {
                if (in != null)
                {
                    in.close();
                 }
                if (out != null) 
                {
                    out.close();
                 }
             }
            

      }catch(IOException e)
      {
    	  e.printStackTrace();
      }
		
	}

	public void modifyFiles(Files file) {
		filesDao.saveFile(file);
		
	}

	public Files getFilesById(Files file) {
		return filesDao.getFilesById(file);
	}
}
